// 拿取数据
import { BookStatus, type Book } from './book'
import {AllData} from './dataBooks'
import { v4 as uuidv4 } from 'uuid';

// 本地存储的键名
const LOCAL_STORAGE_KEY = 'books';

// 从本地存储获取数据
const getLocalBooksData = (): Book[] => {
    const storedData = localStorage.getItem(LOCAL_STORAGE_KEY);
    return storedData ? JSON.parse(storedData) : AllData;
};

// 保存数据到本地存储
const saveLocalBooksData = (books: Book[]): void => {
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(books));
};

// 初始化本地存储数据
export const initLocalStorage = (): void => {
    if (!localStorage.getItem(LOCAL_STORAGE_KEY)) {
        saveLocalBooksData(AllData);
    }
};
initLocalStorage();

// 获取数据
export const getBooksData = (): Book[] => {
    return getLocalBooksData();
};

// 修改或新增时更换该类别的图片
const getTupianData=(book:Book):void=>{
  if(book.status==BookStatus.LITERATURE){
    book.photo=`../../../src/assets/images/book${Math.floor(Math.random() * 3) + 1}.jpg`
  }else if(book.status==BookStatus.SCIENCE){
    book.photo=`../../../src/assets/images/book${Math.floor(Math.random() * 2) + 4}.jpg`
  }else if(book.status==BookStatus.ARTCATEGORY){
    book.photo=`../../../src/assets/images/book${Math.floor(Math.random() * 2) + 6}.jpg`
  }else if(book.status==BookStatus.SOCIETY){
    book.photo=`../../../src/assets/images/book${Math.floor(Math.random() * 2) + 8}.jpg`
  }else if(book.status==BookStatus.OTHER){
    book.photo=`../../../src/assets/images/book${Math.floor(Math.random() * 6) + 10}.jpg`
  }else{
    console.log(`出现错误:${book.status}`);
  }
}

// 新增数据
export const addBookData = (book: Book): boolean => {
    try {
        const books = getLocalBooksData();
        book.id=uuidv4()
        getTupianData(book)
        books.push(book);
        saveLocalBooksData(books);
        return true;
    } catch (error) {
        console.error('添加图书时发生错误:', error);
        return false;
    }
};

// 删除数据
export const deleteBookData = (id: string): boolean => {
    try {
        const books = getLocalBooksData();
        const newBooks = books.filter(book => book.id!== id);
        if (newBooks.length < books.length) {
            saveLocalBooksData(newBooks);
            return true;
        }
        return false;
    } catch (error) {
        console.error('删除图书时发生错误:', error);
        return false;
    }
};

// 修改数据
export const updateBookData = (book: Book): boolean => {
    try {
        const books = getLocalBooksData();
        const index = books.findIndex(b => b.id === book.id);
        if (index!== -1) {
            books[index] = book;
            saveLocalBooksData(books);
            console.log('图书更新成功');
            return true;
        }
        console.error('未找到要更新的图书记录');
        return false;
    } catch (error) {
        console.error('更新图书时发生错误:', error);
        return false;
    }
};
